package risoe.syslab.fhnew.hw.knx;

/*
 * Copyright (c) 2012-2014, Technical University of Denmark (DTU)
 * All rights reserved.
 * 
 * The Flexhouse 2.0 platform ("this software") is licensed under the
 * BSD 3-clause license.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   - Neither the name of DTU nor the names of its contributors may be used to
 *     endorse or promote products derived from this software without specific
 *     prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE TECHNICAL UNIVERSITY OF DENMARK BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import risoe.syslab.fhnew.config.AbstractIOConfig;
import risoe.syslab.fhnew.hw.KNXInterface;
import risoe.syslab.fhnew.hw.knx.KNXConstants.DPTId;
import tuwien.auto.calimero.GroupAddress;
import tuwien.auto.calimero.datapoint.CommandDP;
import tuwien.auto.calimero.exception.KNXException;
import tuwien.auto.calimero.exception.KNXFormatException;
import tuwien.auto.calimero.process.ProcessCommunicator;
import tuwien.auto.calimero.process.ProcessEvent;

/**
 * Superclass for KNX sensors and actuators
 * @author M. Svendsen
 */
public abstract class KNXDevice{
	private GroupAddress mAddress;
	private CommandDP mDatapoint;
	private DPTId mDPTId;
	private KNXInterface mKNXInterface;

	/**
	 * Constructs a new device using a string formatted as "x.x.x" or "x/x/x"
	 * @param groupAddress
	 * @param config an abstractIOConfig representing the device
	 * @param a reference to the appropriate KNXInterface
	 */
	public KNXDevice(String groupAddress, AbstractIOConfig config, KNXInterface intf) {
		try {
			mAddress = new GroupAddress(groupAddress);
		} catch (KNXFormatException e) {
			intf.getLogger().logEvent(getName(), "Formatting Error", "Error creating KNX GroupAddress for device: "+
					config.getName()+" with address: "+groupAddress);
		}
		mDPTId = KNXConstants.DPTMap.get(config.getType());
		mDatapoint = new CommandDP(mAddress, config.getName(), mDPTId.mMainNumber, mDPTId.mId);
		mKNXInterface = intf;
	}
	
	/**
	 * @return the name of this device
	 */
	public String getName(){
		return mDatapoint.getName();
	}
	
	/**
	 * @return the KNXInterface governing this device
	 */
	public KNXInterface getInterface(){
		return mKNXInterface;
	}
	
	/**
	 * @return the type of this device as a DPTId
	 */
	public DPTId getDPT(){
		return mDPTId;
	}
	
	/**
	 * @return the GroupAddress of this device
	 */
	public GroupAddress getGroupAddress(){
		return mAddress;
	}
	
	/**
	 * @return the DataPoint of this device
	 */
	public CommandDP getDataPoint(){
		return mDatapoint;
	}
	
	/**
	 * Translates the contents of a ProcessEvent
	 * @param event to process
	 * @return string containing the value of the event and the unit, i.e. (200 W)
	 */
	public String eventToValue(ProcessEvent event){
		mDPTId.mTranslator.setData(event.getASDU());
		return mDPTId.mTranslator.getValue();
	}
	
	/**
	 * Translates a value to an array of bytes
	 * @param value to process
	 * @return byte array containing the data of the event
	 */
	public byte[] valueToEvent(String value){
		try {
			mDPTId.mTranslator.setValue(value);
		} catch (KNXFormatException e) {}
		return mDPTId.mTranslator.getData();
	}
	
	/**
	 * @return a double value based on a String. Default implementation is based on a String containing a value and a unit, i.e. "200 W"
	 */
	public double getDoubleValue(String value){
		return Double.parseDouble(value.split(" ")[0].trim());
	}
	
	/**
	 * Returns a double representing this event. Default implementation is based on a String containing a value and a unit, i.e. "200 W".
	 * @param event that should be translated
	 * @return a double representing the original String contained in the ProcessEvent, i.e. "200 W", with the unit removed and the value cast to a double
	 */
	public double getDoubleValue(ProcessEvent event){
		return Double.parseDouble(eventToValue(event).split(" ")[0].trim());
	}
	
	/**
	 * Function to read from this device if applicable. Can be overridden. 
	 * Use this to force a new read operation to be carried out on the KNX bus.
	 * @return the read value
	 */
	public String read(){
		KNXInterface intf = getInterface();
		int acknowledged = 0;
		while (acknowledged < KNXConstants.KNX_MAX_RETRIES){
			try {
				ProcessCommunicator comm = intf.getProcessCommunicator();
				synchronized (comm) {
					return comm.read(getDataPoint());
				}
			} catch (KNXException e) {
				// No acknowledge received. try again
				System.out.println("KNX Communication Timeout. Trying again...");
				acknowledged++;
			}
		}
		
		// Read operation timed out! Log this error
		getInterface().getLogger().logEvent(getInterface().getName(), "Read Error", 
				"Error reading from device: "+getName()+" at address: "+getGroupAddress());
		return null;
	}

	/**
	 * Returns a string containing information about this device
	 */
	public String toString() {
		return "device: "+getName()+", "+mAddress.toString()+", "+mDatapoint.getDPT();
	}
}
